package org.gap.wizards.creature;

import java.awt.Point;

import net.slashie.libjcsi.CharKey;

import org.gap.wizards.views.ViewPlatform;
import org.gap.wizards.views.ViewPlatform.Color;
import org.gap.wizards.world.Location;
import org.gap.wizards.world.Movement;

public class TargetCreatureSelecor implements SelectCreature {
	private final ViewPlatform console;
	private char lastKeyPressed;
	
	public TargetCreatureSelecor(ViewPlatform console) {
		this.console = console;
	}
	
	@Override
	public Creature select(Location location) {
		Point targetLocation = location.getCharacterLocation();
		console.saveBuffer();
		CharKey key = console.getKeyPressed();
		char pressed = key.toString().charAt(0);
		Creature creature = null;
		while (Movement.isValid(pressed)) {
			console.restore();
			Movement direction = Movement.from(pressed);
			targetLocation = direction.adjustLocation(targetLocation);
			char symbol = console.peekSymbol(targetLocation);
			Color color = console.peekColor(targetLocation);
			creature = getCreature(location, targetLocation);
			if (creature != null) {
				console.setBackground(Color.YELLOW_GREEN);
			} else {
				console.setBackground(Color.RED);
			}
			console.print(targetLocation.x, targetLocation.y, color, symbol);
			console.setBackground(Color.BLACK);
			console.refresh();
			key = console.getKeyPressed();
			pressed = key.toString().charAt(0);
		}
		
		lastKeyPressed = pressed;
		return creature;
	}

	private Creature getCreature(Location location, Point targetLocation) {
		for (Object each : location.getAllFromLocation(targetLocation)) {
			if (each instanceof Creature) {
				return (Creature)each;
			}
		}
		return null;
	}

	public char lastKeyPressed() {
		return lastKeyPressed;
	}
}
